package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

type Customer struct {
	Cid    int
	Name   string
	Gender string
	Age    int8
	Email  string
}

func NewCustomer(cid int, name string, gender string, age int8, email string) Customer {

	return Customer{
		Cid:    cid,
		Name:   name,
		Gender: gender,
		Age:    age,
		Email:  email,
	}
}

type CustomerService struct {
	customers   []Customer
	customersId int
}

func NewCustomerService(customers []Customer, customersId int) CustomerService {
	return CustomerService{customers, customersId}
}

func (cs *CustomerService) findById(id int) int {
	index := -1
	for i := 0; i < len(cs.customers); i++ {

		if cs.customers[i].Cid == id {
			index = i
		}
	}
	return index
}

func (cs *CustomerService) nextChoice() (b bool) {
	// 引导用户选择继续还是返回
	fmt.Print("返回上一层【回车】,继续该操作【C/c】,退出【Q/q】:")
	var Choice string
	fmt.Scanln(&Choice)
	if strings.ToUpper(Choice) == "C" {
		b = true
	} else if strings.ToUpper(Choice) == "Q" {
		os.Exit(0)
	}
	return
}

func (cs *CustomerService) addCustomer() {
	for true {
		// 引导用户输入学号和姓名
		fmt.Printf("\033[1;35;40m%s\033[0m\n", "---------------------------添加客户开始-----------------------------")
		// 引导用户输入
		var name string
		fmt.Print("请输入客户姓名：")
		fmt.Scan(&name)

		var gender string
		fmt.Print("请输入客户性别：")
		fmt.Scan(&gender)

		var age int8
		fmt.Print("请输入客户年龄：")
		fmt.Scan(&age)

		var email string
		fmt.Print("请输入客户邮箱：")
		fmt.Scan(&email)

		// 创建客户的map对象
		cs.customersId++ // 客户编号不需要输入，系统自增即可
		newCustomer := NewCustomer(cs.customersId, name, gender, age, email)
		// 添加客户map对象添加到客户切片中
		cs.customers = append(cs.customers, newCustomer)
		fmt.Printf("\033[1;35;40m%s\033[0m\n", "---------------------------添加客户完成-----------------------------")
		goOn := cs.nextChoice()
		if !goOn {
			break
		}
	}
}

func (cs *CustomerService) listCustomer() {
	for true {
		fmt.Printf("\033[1;32;40m%s\033[0m\n", "----------------------------------客户列表开始----------------------------")
		for _, customer := range cs.customers {
			fmt.Printf("\u001B[1;39;45m编号：%-8d 姓名：%-8s 性别：%-8s 年龄：%-8d 邮箱：%-10s \u001B[0m\n",
				customer.Cid, customer.Name, customer.Gender, customer.Age, customer.Email)
		}
		fmt.Printf("\033[1;32;40m%s\033[0m\n", "----------------------------------客户列表完成----------------------------")
		goOn := cs.nextChoice()
		if !goOn {
			break
		}
	}
}
func (cs *CustomerService) updateCustomer() {
	fmt.Printf("\033[1;36;40m%s\033[0m\n", "---------------------------客户修改开始----------------------------")
	for true {
		var updateCid int
		fmt.Print("请输入更新客户编号(-1退出)：")
		fmt.Scan(&updateCid)
		if updateCid == -1 {
			return
		}
		updateIndex := cs.findById(updateCid)
		if updateIndex == -1 {
			fmt.Println("删除失败，输入的编号ID不存在")
			continue
		}

		// 引导用户输入
		var name string
		fmt.Printf("请输入客户姓名(%s)：", cs.customers[updateIndex].Name)
		fmt.Scanln(&name)

		var gender string
		fmt.Printf("请输入客户性别(%s)：", cs.customers[updateIndex].Gender)
		fmt.Scanln(&gender)

		var age int8
		fmt.Printf("请输入客户年龄(%d)：", cs.customers[updateIndex].Age)
		fmt.Scanln(&age)

		var email string
		fmt.Printf("请输入客户邮箱(%s)：", cs.customers[updateIndex].Email)
		fmt.Scanln(&email)

		if age != 0 {
			cs.customers[updateIndex].Age = age
		}
		if name != "" {
			cs.customers[updateIndex].Name = name
		}
		if gender != "" {
			cs.customers[updateIndex].Gender = gender
		}
		if email != "" {
			cs.customers[updateIndex].Email = email
		}

		fmt.Printf("\033[1;36;40m%s\033[0m\n", "---------------------------客户修改完成----------------------------")
		goOn := cs.nextChoice()
		if !goOn {
			break
		}
	}
}

func (cs *CustomerService) deleteCustomer() {
	for true {
		fmt.Printf("\033[1;31;40m%s\033[0m\n", "---------------------------删除客户开始----------------------------")
		var delCid int
		fmt.Print("请输入删除客户编号：")
		fmt.Scan(&delCid)

		delIndex := cs.findById(delCid)
		if delIndex == -1 {
			fmt.Println("删除失败，输入的编号ID不存在")
			continue
		}
		cs.customers = append(cs.customers[:delIndex], cs.customers[delIndex+1:]...)
		fmt.Printf("\033[1;31;40m%s\033[0m\n", "---------------------------删除客户完成----------------------")
		goOn := cs.nextChoice()
		if !goOn {
			break
		}
	}
}

func (cs *CustomerService) keepCustomers() {

	customersJsonBytes, _ := json.Marshal(cs.customers)
	err := ioutil.WriteFile("customers.json", customersJsonBytes, 0666)
	if err != nil {
		return
	}

	fmt.Printf("\033[1;31;40m%s\033[0m\n", "---------------------------保存完成----------------------")

}

func main() {
	var customers []Customer
	customersJsonBytes, err := ioutil.ReadFile("customers.json")
	if err != nil {
		return
	}
	json.Unmarshal(customersJsonBytes, &customers)
	cs := NewCustomerService(customers, customers[len(customers)-1].Cid)
	for true {
		fmt.Printf("\033[1;30;42m%s\033[0m\n", `
----------------客户信息管理系统--------------
           1、添加客户
           2、查看客户
           3、更新客户
           4、删除客户
           5、保存
           6、退出
-------------------------------------------
`)

		var choice int
		fmt.Printf("\033[1;38;40m%s\033[0m", "请输入选择【1-5】:")
		stdin := bufio.NewReader(os.Stdin)
		fmt.Fscan(stdin, &choice)

		switch choice {
		case 1:
			cs.addCustomer()
		case 2:
			cs.listCustomer()
		case 3:
			cs.updateCustomer()
		case 4:
			cs.deleteCustomer()
		case 5:
			cs.keepCustomers()
		case 6:
			os.Exit(0)
		default:
			fmt.Println("按要求输入数字，请重新输入")
		}
	}

}
